package com.fivefaces.ide.plugins;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.vfs.VirtualFile;

/**
 * User: imran.khan
 * Date: 6/04/11
 * Time: 11:24 AM
 */
public class ShowConsole extends AnAction {
    private CommandBuilderFactory factory;

    public ShowConsole() {
        factory = new CommandBuilderFactory();
    }

    public void actionPerformed(AnActionEvent e) {
        VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);

        if (virtualFile != null) {
            String filePath = extractDirectoryPath(virtualFile);
            CommandBuilder builder = factory.getInstance();
            String [] command = builder.buildCommand(filePath);
            executeCommand(command);
        }
    }

    private String extractDirectoryPath(VirtualFile virtualFile) {
        String result;
        if (virtualFile.isDirectory()) {
            result = virtualFile.getPath();
        } else  {
            result = virtualFile.getParent().getPath();
        }
        return result;
    }

    private void executeCommand(String... command) {
        try {
            Util.printCommand(command);
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream();
            processBuilder.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
